package com.lw.udpchat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @author LW
 * @2020/9/19 12:50
 */
public class TalkReceive implements Runnable {
    DatagramSocket socket = null;

    private int port;
    private String msgName;

    public TalkReceive(int port, String msgName) {
        this.port = port;
        this.msgName = msgName;
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {

        while (true){
            try {
                //准备接收包裹
                byte[] buffer = new byte[1024];
                DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);

                socket.receive(packet);//阻塞式接收包裹
                byte[] data = packet.getData();
                String receivedatas = new String(data, 0, data.length);

                System.out.println(msgName+": "+receivedatas);
                if(receivedatas.equals("bye")){
                    //接收单因为数据长度的问题，equals比较结果为false，连接不会断开
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }


        }

        socket.close();
    }
}
